<template>
	<view class="adup-qtbz page-bg">
		<view class="fm-title">
			<view class="title"><label class="line-icon" :style="{'background': '#00c3c3'}"></label>{{title}}</view>
			<u-button :loading="sb.load" type="success" @click="submitFm">
				<u-icon v-if="!sb.load" name="edit-pen-fill" color="#fff"
					:custom-style="{'margin-right': '10rpx'}"></u-icon>
				提交修改
			</u-button>
		</view>

		<u-form :model="fm" ref="bzfm" v-if="fm">
			<view class="my-fm">
				<view class="f-item no-box">
					<u-form-item>
						<view class="i-row">
							<view class="r-title">公里数</view>
							<view class="r-con">
								<u-input v-model="fm.currentKilo" :type="'digit'" :maxlength="8" :input-align="'right'"
									:clearable="false" :custom-style="{'color': '#00C3CE'}" placeholder="当前公里数" /><label
									class="i-r-text">公里</label>
							</view>
						</view>
					</u-form-item>
					<template v-if="title != '其他费用'">

						<u-form-item>
							<view class="i-row">
								<view class="r-title">开始日期</view>
								<view class="r-con">
									<MyDateTime :name="'costSdate'" :showType="1" :datePlaceholder="'开始日期'"
										:dateTime="fm.costSdate" @myClick="setDateTime"></MyDateTime>
								</view>
							</view>
						</u-form-item>

						<u-form-item>
							<view class="i-row">
								<view class="r-title">结束日期</view>
								<view class="r-con">
									<MyDateTime :name="'costEdate'" :showType="1" :datePlaceholder="'结束日期'"
										:dateTime="fm.costEdate" @myClick="setDateTime"></MyDateTime>
								</view>
							</view>
						</u-form-item>
					</template>
					<template v-else>
						<u-form-item>
							<view class="i-row">
								<view class="r-title">记账日期</view>
								<view class="r-con">
									<MyDateTime :name="'jzDate'" :showType="1" :datePlaceholder="'记账日期'"
										:dateTime="fm.jzDate" @myClick="setDateTime"></MyDateTime>
								</view>
							</view>
						</u-form-item>
					</template>

					<u-form-item>
						<view class="i-row">
							<view class="r-title">记账金额</view>
							<view class="r-con">
								<u-input v-model="fm.jzMoney" :type="'digit'" :maxlength="6" :input-align="'right'"
									:clearable="false" :custom-style="{'color': '#00C3CE'}"
									:placeholder="'请输入记账金额'" /><label class="i-r-text">元</label>
							</view>
						</view>
					</u-form-item>

					<u-form-item>
						<view class="i-row">
							<view class="r-title">支付方式</view>
							<view class="r-con">
								<MySelect :title="'支付方式'" :name="'payWay'" :list="payWayList" :defval="fm.payWay"
									@seledItem="mySeledMd"></MySelect>
							</view>
						</view>
					</u-form-item>

					<u-form-item>
						<view class="i-row-textarea">
							<view class="r-title">备注</view>
							<view class="r-con">
								<u-input v-model="fm.jzRemark" :type="'textarea'" :custom-style="{'color': '#00C3CE'}"
									:placeholderStyle="'color: #f000000;'" :clearable="false" :auto-height="true"
									:height="150" :maxlength="200" :placeholder="'请填写报账备注，最多输入200个字（选填）'" />
							</view>
						</view>
					</u-form-item>

					<u-form-item :border-bottom="false">
						<view class="i-row-textarea">
							<view class="r-title">报账凭证<label class="r-title-tip">（最多上传6张图片）</label></view>
							<view class="r-con">
								<u-upload ref="bzUf" width="200" height="200" max-count="6" :file-list="fm.uflist"
									:action="ufAction" :header="ufHeader" :name="'files'"
									:form-data="{ftype: fm.bzType.key+'_IMG', orderNum: fm.plateNum, uid: fm.uid}"
									:max-size="1024*1024*30"></u-upload>
							</view>
						</view>
					</u-form-item>
				</view>
			</view>
		</u-form>

		<u-toast ref="qtoast" />
	</view>
</template>

<script>
	import MySelect from '@/components/my-select/my-select.vue';
	import MyDateTime from '@/components/my-date-time/my-date-time.vue';

	export default {
		components: {
			MySelect,
			MyDateTime
		},
		data() {
			return {
				plateNum: '',
				// 维修详情输入框样式
				inpBtnStyl: {
					'color': '#00C3CE',
					'padding-right': '30rpx'
				},

				// 文件上传地址
				ufAction: this.C.upfileUrl,
				// 文件上传请求头信息
				ufHeader: {
					'token': uni.getStorageSync(this.C.uuid)
				},
				// 旧文件数据
				flist: [],

				// 表单对象
				fm: null,
				// 提交参数
				sb: {
					load: false
				},

				// 标题
				title: '其他报账',

				// 维修支付方式列表
				payWayList: [{
						val: 'JZ_PAY',
						text: '记账'
					},
					{
						val: 'CASH_PAY',
						text: '现金'
					},
				]
			}
		},
		onLoad(e) {
			console.log('传入的参数', e);

			this.getBzDetail(e.id);
		},
		methods: {
			// 弹框列表选择
			mySeledMd(e) {
				this.fm[e.name] = e.obj;
			},
			// 选择日期时间
			setDateTime(e) {
				this.fm[e.name] = e.obj;
			},
			// 获取-报账详情
			async getBzDetail(id) {
				const that = this;

				let res = await that.$u.api.getBzDetail({
					id: id
				});
				if (res.code == 1) {
					let o = res.data;

					// 根据报账类型初始化对应数据
					let p = {};
					// 修改id
					p.id = o.id;
					// 报账车辆车牌

					that.plateNum = o.plateNum;
					that.title = o.moneyTypeName;
					p.plateNum = o.plateNum;
					// 报账类型
					if (o.moneyTypeName == '其他费用') {
						p.bzType = 'QTJZ';
					} else if (o.moneyTypeName == '月停车费') {
						p.bzType = 'YTCF';
					} else if (o.moneyTypeName == '月洗车费') {
						p.bzType = 'YXCF';
					}

					// 加油金额
					p.jzMoney = o.reimMoney;
					let payWayList = [{
							val: 'ACCOUNTING',
							text: '记账'
						},
						{
							val: 'CASH',
							text: '现金'
						},
					]
					// 支付方式
					if (o.payWay) p.payWay = {

						text: o.payWay
					};
					for (let i = 0; i < payWayList.length; i++) {
						if (o.payWay == payWayList[i].text) {
							p.payWay.val = payWayList[i].val
						}
					}

					// 月停车开始日期
					p.costSdate = {
						date: o.costStime,
						time: ''
					};
					// 月停车结束日期
					p.costEdate = {
						date: o.costEtime,
						time: ''
					};

					// 报账日期
					p.jzDate = {
						date: that.datatime(o.payTime),
						time: ''
					};
					// 备注
					p.currentKilo = o.currentKilo;
					// 备注
					p.jzRemark = o.remark;
					// 图片id
					p.fids = [];
					// 默认图片数组
					let flist = [];
					if (o.reimVoucherUrl) {
						let fs = o.reimVoucherUrl.split(',');
						fs.forEach(it => {
							flist.push({

								url: 'https://cba360.com' + it
							});
						});
					}
					that.flist = flist; // 保存起来
					p.uflist = flist;

					that.fm = p;
					console.log('赋值', that.fm);
				}
			},
			// 表单验证
			valFm() {
				const that = this,
					U = that.U,
					FV = that.FV;
				let fg = true,
					ps = U.scopy(that.fm),
					p = {};

				p.jzType = ps.bzType;
				p.id = ps.id;

				if (p.jzType == 'QTJZ') {
					p.moneyTypeId = 39;
				} else if (p.jzType == 'YTCF') {
					p.moneyTypeId = 21;
				} else if (p.jzType == 'YXCF') {
					p.moneyTypeId = 22;
				}

				if (p.jzType != 'QTJZ') {
					if (fg) {
						let costSdate = ps.costSdate.date;
						if (!costSdate) {
							fg = U.qinfo('[停车开始日期]不能为空');
						} else if (U.str2date(costSdate + ' 00:00:00').getTime() > new Date().getTime()) {
							fg = U.qinfo('[停车开始日期]不能大于当前时间');
						} else {
							p.costStartTime = costSdate;
						}
					}

					if (fg) {
						let costEdate = ps.costEdate.date;
						if (!costEdate) {
							fg = U.qinfo('[停车结束日期]不能为空');
						} else if (U.str2date(costEdate + ' 00:00:00').getTime() > new Date().getTime()) {
							fg = U.qinfo('[停车结束日期]不能大于当前时间');
						} else {
							if (U.str2date(costEdate + ' 00:00:00').getTime() < U.str2date(ps.costSdate + ' 00:00:00')
								.getTime()) {
								fg = U.qinfo('[停车结束日期]不能小于[停车开始日期]');
							} else {
								p.costEndTime = costEdate;
							}
						}
					}
				} else {
					if (fg) {
						let jzDate = ps.jzDate.date;
						if (!jzDate) {
							fg = U.qinfo('[记账日期]不能为空');
						} else if (U.str2date(jzDate + ' 00:00:00').getTime() > new Date().getTime()) {
							fg = U.qinfo('[记账日期]不能大于当前时间');
						} else {
							p.payTime = jzDate;
						}
					}
				}

				if (fg) {
					let jzMoney = ps.jzMoney;
					if (!jzMoney && jzMoney != 0) {
						fg = U.qinfo('[记账金额]不能为空');
					} else if (!FV.isFloat(jzMoney)) {
						fg = U.qinfo('[记账金额]格式错误');
					} else {
						p.reimMoney = jzMoney;
					}
				}

				if (fg) {
					let payWay = ps.payWay.val;
					if (!payWay) {
						fg = U.qinfo('[支付方式]不能为空');
					} else {
						p.payWay = payWay;
					}
				}
				if (fg) {
					let currentKilo = ps.currentKilo;
					if (!currentKilo || currentKilo < 0) {
						fg = U.qinfo('[当前公里数]不能为空');
					} else {
						p.currentKilo = currentKilo;
					}
				}
				if (fg) {
					let jzRemark = ps.jzRemark;
					if (jzRemark && jzRemark.length > 200) {
						fg = U.qinfo('[备注]最多填写200个字');
					} else {
						p.remark = jzRemark;
					}
				}

				if (fg) {
					let uflist = that.$refs.bzUf.lists;
					if (uflist.length == 0) {
						fg = U.qinfo('至少需要上传一张停车费小票图片');
					} else {
						let fids = [];
						uflist.forEach(it => {
							if (it.url && it.url.indexOf('_img') != -1) { // 本地图片
								let is = that.flist.find(fit => it.url.indexOf(fit.url) != -1);
								let url = is.url.split('.com')[1]
								console.log(url, 'url')
								fids.push(url);
							} else { // 新传图片
								if (it.response && it.response.data) fids.push(it.response.data.file.url);
							}
						});
						console.log(fids)
						if (fids.length == 0) {
							fg = U.qinfo('上传图片' + uflist.length + '张，成功' + fids.length + '张');
						} else {
							p.reimVoucherUrl = fids.join(',');
						}
					}
				}

				return fg ? {
					staffReimInfo: [p]
				} : fg;
			},
			// 提交表单
			submitFm() {
				let that = this,
					ps = that.valFm(),
					U = that.U,
					sb = that.sb;

				if (ps != false) {
					ps.plateNum = that.plateNum
					console.log('提交参数', ps);
					sb.load = true;
					that.$u.api.adupAllUnRouteBz(ps).then((res) => {
						if (!res || res.code != 1) {
							sb.load = false;
						} else {
							U.qtoast(that, {
								title: res.msg,
								type: 'success',
								duration: 1000,
								callback: function() {
									sb.load = false;

									// 刷新父级列表（刷新未报销的列表）
									uni.$emit('refJzList', 0);
									// 返回上一页
									uni.navigateBack({
										delta: 1
									});
								}
							});
						}
					}).catch(err => {
						sb.load = false;
					});
				}
			},
			datatime(e) {
				let originalDateTimeString = e;
				let date = new Date(originalDateTimeString);

				let year = date.getFullYear();
				let month = String(date.getMonth() + 1).padStart(2, '0');
				let day = String(date.getDate()).padStart(2, '0');
				let hours = String(date.getHours()).padStart(2, '0');
				let minutes = String(date.getMinutes()).padStart(2, '0');
				let seconds = String(date.getSeconds()).padStart(2, '0');

				let formattedDateTimeString = `${year}-${month}-${day}`;
				return formattedDateTimeString
			},

		}
	}
</script>

<style lang="scss">
	.adup-qtbz {
		padding-top: 80rpx;
		padding-bottom: 10rpx;

		.f-item {
			margin: 10rpx !important;
		}
	}
</style>